package com.ruoyi.app.config;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.app.config.properties.RsaAuthProperties;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@EnableConfigurationProperties(RsaAuthProperties.class)
@Configuration
public class RsaConfig {


    @Autowired
    RsaAuthProperties rsaAuthProperties;


    @Bean
    public FilterRegistrationBean zkqFilter() {
        return new FilterRegistrationBean((servletRequest, servletResponse, filterChain) -> {

            if(servletRequest instanceof HttpServletRequest){
                HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
                RsaHttpServletRequestWrapper rsaHttpServletRequestWrapper = null;
                try {
                    rsaHttpServletRequestWrapper = new RsaHttpServletRequestWrapper(httpRequest);
                    filterChain.doFilter(rsaHttpServletRequestWrapper, servletResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                    ServletUtils.renderString((HttpServletResponse) servletResponse, JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED, "参数错误")));
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }) {{
            setOrder(rsaAuthProperties.getOrder());
            setName(rsaAuthProperties.getName());
            setEnabled(rsaAuthProperties.isEnabled());
            addUrlPatterns(rsaAuthProperties.getUrls());
        }};
    }
}
